<template>
  <el-dialog
    :title="form.id ? '编辑用户' : '新增用户'"
    v-model="dialogVisible"
    width="500px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="80px"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" placeholder="请输入用户名" :disabled="!!form.id" />
      </el-form-item>

      <el-form-item label="姓名" prop="realName">
        <el-input v-model="form.realName" placeholder="请输入姓名" />
      </el-form-item>

      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入手机号" />
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" placeholder="请输入邮箱" />
      </el-form-item>

      <el-form-item label="角色" prop="roleId">
        <el-select v-model="form.roleId" placeholder="请选择角色">
          <el-option
            v-for="item in roleOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="状态">
        <el-radio-group  v-model="form.status">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="密码" prop="password" v-if="!form.id">
        <el-input
          v-model="form.password"
          type="password"
          placeholder="请输入密码"
          show-password
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, defineProps, defineEmits, computed, watch, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { addUser, updateUser } from '@/api/user'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  userData: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['update:visible', 'refresh'])

// 控制弹窗显示
const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

// 表单数据
const formRef = ref()
const form = reactive({
  id: undefined,
  username: '',
  realName: '',
  phone: '',
  email: '',
  roleId: undefined,
  status: 1,
  password: ''
})

// 表单校验规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 4, max: 20, message: '长度在 4 到 20 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_-]+$/, message: '只能包含字母、数字、下划线和横线', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    // { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  roleId: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  // password: [
  //   { required: true, message: '请输入密码', trigger: 'blur', when: (form) => !form.id },
  //   { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
  //   {
  //     pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{6,20}$/,
  //     message: '密码必须包含大小写字母和数字',
  //     trigger: 'blur',
  //     when: (form) => !form.id
  //   }
  // ]
}

// 角色选项
const roleOptions = ref([{id:1, name: '管理员'},{id:2, name: '医生'},{id:3, name: '用户'}])

// 提交表单前的数据处理
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const submitData = { ...form }
        // 编辑时不提交密码字段
        if (submitData.id) {
          delete submitData.password
        }

        if (form.id) {
          await updateUser(submitData)
          ElMessage.success('更新成功')
        } else {
          await addUser(submitData)
          ElMessage.success('新增成功')
        }
        dialogVisible.value = false
        emit('refresh')
      } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error(error.response?.data?.message || '操作失败')
      }
    }
  })
}

// 优化表单重置逻辑
const resetForm = () => {
  const defaultForm = {
    id: undefined,
    username: '',
    realName: '',
    phone: '',
    email: '',
    roleId: undefined,
    status: 1,
    password: ''
  }
  Object.assign(form, defaultForm)
  formRef.value?.resetFields()
}

// 弹窗关闭处理
const handleClose = () => {
  resetForm()
  emit('update:visible', false)
}

// 监听用户数据变化
watch(() => props.userData, (val) => {
  if (val && val.id) {
    nextTick(() => {
      Object.assign(form, val)
    })
  } else {
    resetForm()
  }
}, { immediate: true })

</script>

<style lang="scss" scoped>
.el-select {
  width: 100%;
}

.el-input-number {
  width: 100%;
}

:deep(.el-form-item__label) {
  font-weight: normal;
}

:deep(.el-radio-group) {
  width: 100%;
}
</style>
